//
//  TZBigPictureVc.m
//  BSBDJ
//
//  Created by user on 16/5/26.
//  Copyright © 2016年 Burning. All rights reserved.
//

#import "TZBigPictureVc.h"
#import "TZEssenceItem.h"
#import <Photos/Photos.h>
#import <SVProgressHUD.h>
@interface TZBigPictureVc ()<UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UIProgressView *progress_View;

@property (nonatomic, weak) UIScrollView *scrollView;

@property (nonatomic, weak) UIImageView *pictureImage;
@end

@implementation TZBigPictureVc
static NSString * TZAssetCollectionTitle = @"百思不得姐";

- (UIImageView *)pictureImage{
    if (_pictureImage == nil) {
        UIImageView *picture = [UIImageView new];
        picture.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backClick:)];
        tap.delegate = self;
        [picture addGestureRecognizer:tap];
        self.pictureImage = picture;
        [self.scrollView addSubview:picture];
    }
    return _pictureImage;
}

- (UIScrollView *)scrollView{
    if (_scrollView == nil) {
        UIScrollView *scrollView = [UIScrollView new];
        scrollView.frame = CGRectMake(0, 0, TZScreenW, TZScreenH);
        [self.view insertSubview:scrollView atIndex:0];
        _scrollView = scrollView;
    }
    return _scrollView;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGFloat width = TZScreenW;
    //如果是大图 contentsize 为根据屏幕计算的长度
    if (self.item.is_BigImage){
        CGFloat height = width *self.item.height / self.item.width;
        self.pictureImage.frame = CGRectMake(0, 0, width, height);
        self.scrollView.contentSize = self.pictureImage.size;
    }else{
        //如果是小图 scrollView的不用设置 contentsize
        CGFloat height = width *self.item.height / self.item.width;
        self.pictureImage.frame = CGRectMake(0, 0, width, height);
        self.pictureImage.center = CGPointMake(TZScreenW *0.5, TZScreenH *0.5);
    }
   
    
    [self.pictureImage sd_setImageWithPreviousCachedImageWithURL:[NSURL URLWithString:self.item.large_image] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        self.progress_View.hidden = NO;
        CGFloat progress = 1.0 *receivedSize / expectedSize;
        [self.progress_View setProgress:progress animated:YES];
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.progress_View.hidden = YES;
        self.pictureImage.image = image;
        
    }];
    
}
- (IBAction)backClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)shareBtnClick:(id)sender {
}
- (IBAction)saveBtnClick:(id)sender {
    //>判断请求用户状态
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    //>请求用户选择授权状态
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            switch (status) {
                    //>用户拒绝
                case PHAuthorizationStatusDenied:
                    if (oldStatus == PHAuthorizationStatusNotDetermined) {
                        [SVProgressHUD showWithStatus:@"请开启相册"];
                    }
                    break;
                    //>系统拒绝
                case PHAuthorizationStatusRestricted:
                    [SVProgressHUD showErrorWithStatus:@"被系统拒绝"];
                    break;
                    //>用户接受
                case PHAuthorizationStatusAuthorized:
                    [self saveImage];

                    break;
                    
                default:
                    break;
            }
        });
    }];
    
}

- (void)setupUI
{
    
}
- (void)initView{
    
}

- (void)saveImage{
    // PHAsset : 一个资源, 比如一张图片\一段视频
    // PHAssetCollection : 一个相簿
    
    // PHAsset的标识, 利用这个标识可以找到对应的PHAsset对象(图片对象)
    __block NSString *assetLocalIdentifier = nil;
    
    // 如果想对"相册"进行修改(增删改), 那么修改代码必须放在[PHPhotoLibrary sharedPhotoLibrary]的performChanges方法的block中
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // 1.保存图片A到"相机胶卷"中
        // 创建图片的请求
        assetLocalIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:self.pictureImage.image].placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success == NO) {
            [self showError:@"保存图片失败!"];
            return;
        }
        
        // 2.获得相簿
        PHAssetCollection *createdAssetCollection = [self createdAssetCollection];
        if (createdAssetCollection == nil) {
            [self showError:@"创建相簿失败!"];
            return;
        }
        
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            // 3.添加"相机胶卷"中的图片A到"相簿"D中
            
            // 获得图片
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
            
            // 添加图片到相簿中的请求
            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdAssetCollection];
            
            // 添加图片到相簿
            [request addAssets:@[asset]];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (success == NO) {
                [self showError:@"保存图片失败!"];;
            } else {
                [self showSuccess:@"保存图片成功!"];;
            }
        }];
    }];
}


/**
 *  获得相簿
 */
- (PHAssetCollection *)createdAssetCollection
{
    // 从已存在相簿中查找这个应用对应的相簿
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *assetCollection in assetCollections) {
        if ([assetCollection.localizedTitle isEqualToString:TZAssetCollectionTitle]) {
            return assetCollection;
        }
    }
    
    // 没有找到对应的相簿, 得创建新的相簿
    
    // 错误信息
    NSError *error = nil;
    
    // PHAssetCollection的标识, 利用这个标识可以找到对应的PHAssetCollection对象(相簿对象)
    __block NSString *assetCollectionLocalIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 创建相簿的请求
        assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:TZAssetCollectionTitle].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    
    // 如果有错误信息
    if (error) return nil;
    
    // 获得刚才创建的相簿
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionLocalIdentifier] options:nil].lastObject;
}


- (void)showSuccess:(NSString *)text
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showSuccessWithStatus:text];
    });
}

- (void)showError:(NSString *)text
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showErrorWithStatus:text];
    });
}
@end
